<?php
/**
 * BaseController
 *
 * PHP Version 5.4
 *
 * @author liuxu <liuxu2630@foxmail.com>
 */
namespace Home\Controller;

use Model\UserModel;
use Think\Controller;
use Think\Page;
use Think\Upload;

/**
 * Class BaseController
 */
class BaseController extends Controller
{

    public function __construct()
    {
        parent::__construct();
        $this->getUserMessage();
    }

    /**
     * 获取用户信息
     */
    public function getUserMessage()
    {
        $id = cookie('id');
        if (!empty($id)) {
            $userModel = new UserModel();
            $userMessage = $userModel->find($id);
            $this->assign("userMessage", $userMessage);
        }
    }

    /**
     * 验证用户是否登录
     *
     * @method COOKIE
     *
     * @return String
     */
    public function validateLogin()
    {
        $userId = cookie('userId');
        if (empty($userId)) {
            $this->Alert(__ROOT__ . '/Home/User');
        }
    }

    /**
     * 验证用户是否登录(弹窗)
     *
     * @method COOKIE
     *
     * @return String
     */
    public function validateLoginAlert()
    {
        $userId = cookie('userId');
        if (empty($userId)) {
            $this->AlertGoToUrl('请先登录', __ROOT__ . '/Home/User');
        }
    }

    /**
     * 获取用户cookie
     *
     */
    public function getUserIdCookie()
    {
        $userId = cookie('userId');

        return $userId;
    }

    /**
     * 获取时间（几分钟前、几小时前）
     */
    public function time_tran($the_time)
    {
        $now_time = date("Y-m-d H:i:s", time());
        //echo $now_time;
        $now_time = strtotime($now_time);
        $show_time = strtotime($the_time);
        $dur = $now_time - $show_time;
        if ($dur < 0) {
            return $the_time;
        } else {
            if ($dur < 60) {
                return $dur . '秒前';
            } else {
                if ($dur < 3600) {
                    return floor($dur / 60) . '分钟前';
                } else {
                    if ($dur < 86400) {
                        return floor($dur / 3600) . '小时前';
                    } else {
                        if ($dur < 259200) {//3天内
                            return floor($dur / 86400) . '天前';
                        } else {
                            return $the_time;
                        }
                    }
                }
            }
        }
    }

    /**
     *  上传文件
     *
     * @method POST
     *
     */
    public function upload($file)
    {
        $upload = new Upload();
        $upload->maxSize = 1 * 1024 * 1024;  //设置附件上传大小
        $upload->exts = array('jpg', 'gif', 'png', 'jpeg'); //设置附件上传类型
        $upload->savePath = '/Uploads/';
        $upload->rootPath = './Images/';   //设置上传目录
        $upload->saveName = time() . '_' . mt_rand();

        $result = $upload->uploadOne($file);
        if (!$result) {
            $this->AlertBack($upload->getError(), null, 2);
        } else {
            return 'Images' . $result['savepath'] . $result['savename'];
        }
    }

    /**
     *  上传多个文件
     *
     * @method POST
     *
     */
    public function uploadList($file, $size)
    {
        $upload = new Upload();
        $upload->maxSize = $size * 1024;  //设置附件上传大小
        $upload->exts = array('jpg', 'gif', 'png', 'jpeg'); //设置附件上传类型
        $upload->savePath = '/Uploads/';
        $upload->rootPath = './Images/';   //设置上传目录

        $imageFileRest = array();
        /*** 重新整理上传图片 ***/
        for ($i = 0; $i < count($file['name']); $i++) {
            $imageFileRest[$i]['name'] = $file['name'][$i];
            $imageFileRest[$i]['type'] = $file['type'][$i];
            $imageFileRest[$i]['tmp_name'] = $file['tmp_name'][$i];
            $imageFileRest[$i]['error'] = $file['error'][$i];
            $imageFileRest[$i]['size'] = $file['size'][$i];
        }

        $image = '';
        foreach ($imageFileRest as $img) {
            $upload->saveName = time() . '_' . mt_rand();
            if ($img['size'] > $upload->maxSize) {
                $this->AlertBack('单张图片限制' . $size . 'KB以内');
            } else {
                $result = $upload->uploadOne($img);
                if (!$result) {
                    $this->error($upload->getError(), null, 2);
                } else {
                    $image = $image . 'Images' . $result['savepath'] . $result['savename'] . ' ';
                }
            }
        }

        return $image;
    }

    /**
     *  获取分页
     *
     * @method POST
     *
     */
    public function page($model, $where, $pagesize = 10)
    {
        $modelClone = clone $model;
        $count = $model->where($where)->count();
        $model = $modelClone;
        $page = new Page($count, $pagesize);

        $page->parameter = I('get.');

        $model->limit($page->firstRow . ',' . $page->listRows);

        return $page;
    }

    public function AlertBack($_msg)
    {
        header("Content-Type:text/html; charset=utf-8");
        echo "<script type=\"text/javascript\">";
        echo "alert('" . $_msg . "');";
        echo "history.go(-1);";
        echo "</script>";
        exit();
    }

    public function AlertGoToUrl($_msg, $_url)
    {
        header("Content-Type:text/html; charset=utf-8");
        echo "<script type=\"text/javascript\">";
        echo "alert('" . $_msg . "');";
        echo "window.location.href='" . $_url . "'";
        echo "</script>";
        exit();
    }

    public function Alert($_url)
    {
        header("Content-Type:text/html; charset=utf-8");
        echo "<script type=\"text/javascript\">";
        echo "window.location.href='" . $_url . "'";
        echo "</script>";
        exit();
    }

    public function success($_msg, $_url)
    {
        header("Content-Type:text/html; charset=utf-8");
        echo "<script type=\"text/javascript\">";
        echo "alert('" . $_msg . "');";
        echo "window.location.href='" . $_url . "'";
        echo "</script>";
        exit();
    }

    public function error($_msg, $_url)
    {
        header("Content-Type:text/html; charset=utf-8");
        echo "<script type=\"text/javascript\">";
        echo "alert('" . $_msg . "');";
        echo "window.location.href='" . $_url . "'";
        echo "</script>";
        exit();
    }


}